package com.shxc.smarttrade.quotation.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.OpenTrader;
import com.shxc.smarttrade.old.bean.PendingOrder;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.SymbolInfo;
import com.shxc.smarttrade.old.bean.SymbolPrice;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.foreignfragment.AdvancedTransFragment;
import com.shxc.smarttrade.old.foreignfragment.SimpleTransFragment;
import com.shxc.smarttrade.old.iview.IViewRealTimeQuote;
import com.shxc.smarttrade.old.iview.IViewStockChart;
import com.shxc.smarttrade.old.presenter.MainPresenter;
import com.shxc.smarttrade.old.presenter.StockChartPresenter;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

/**
 * Created by jcdev1 on 2017/9/26.
 */

public class AllQuotationActivity extends FragmentActivity implements IViewRealTimeQuote, IViewStockChart {

    @BindView(R.id.tv_ananlyze)
    TextView tvAnanlyze;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.frame_all)
    FrameLayout frameAll;
    @BindView(R.id.btn_trade)
    Button btnTrade;

    private SimpleTransFragment simpleTransFragment;
    private AdvancedTransFragment advancedTransFragment;
    private int mIndex;
    private Fragment[] mFragment;
    private String accessToken = "";
    public int userId = -1;
    public String symbleOne = "";//当前品质
    private String symbleTwo = "";//当前品种加上交叉盘需转换品种
    public String symbolCn = "";//品种中文名
    public int digits = -1;//品种小数点位数
    private StockChartPresenter stockChartPresent;
    private MainPresenter mainPresent;
    private int whatTab = 0;//点击哪个Tab
    private int btnStatus = 0;//底部按钮默认买涨 1：买跌 2：挂单

    public SymbolInfo symbolInfo;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_quotation_activity);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        initData();
    }


    private void initView() {
        CloseAllActivity.getScreenManager().pushActivity(this);
        simpleTransFragment = new SimpleTransFragment();
        advancedTransFragment = new AdvancedTransFragment();
        mFragment = new Fragment[]{simpleTransFragment, advancedTransFragment};
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.frame_layout, simpleTransFragment);
        transaction.add(R.id.frame_layout, advancedTransFragment);
        transaction.show(simpleTransFragment);
        transaction.hide(advancedTransFragment);
        transaction.commit();
    }

    /**
     * 获取用于计算盈亏的基础数据
     */
    private void initData() {
        userId = SpUtils.getInt(this, "userId", -1);
        accessToken = SpUtils.getString(this, "accessToken");
        stockChartPresent = new StockChartPresenter(this);
        mainPresent = new MainPresenter(this);
        Intent intent = getIntent();
        symbleOne = intent.getStringExtra("symbol");
        symbleTwo = intent.getStringExtra("symbol");
        symbolCn = intent.getStringExtra("symbolCn");
        digits = intent.getIntExtra("digits", -1);
        stockChartPresent.getSymbolPrice(accessToken, symbleOne);
        stockChartPresent.getSymboLCalInfo(accessToken, symbleOne, userId);
        mainPresent.startRealTimeQuote(symbleTwo);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mainPresent.stopRealTimerQuote();
        CloseAllActivity.getScreenManager().popActivity(this);
    }

    @OnClick({R.id.tv_ananlyze, R.id.tv_msg, R.id.ll_back, R.id.btn_trade, R.id.ll_chart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ananlyze:
                whatTab = 0;
                setIndexSelected(0);
                changeStatus(0);
                btnTrade.setVisibility(View.GONE);
                break;
            case R.id.tv_msg:
                whatTab = 1;
                setIndexSelected(1);
                changeStatus(1);
                btnTrade.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_back:
                finish();
                break;
            case R.id.btn_trade:
                if (userId == -1) {
                    noLoginGoThere();
                    return;
                }
                if (btnStatus == 0) {//1、买涨
                    EventBus.getDefault().post(new EventDatas(EventContents.ALL_QUOTATION_ACTIVITY_ONE, ""));

                } else if (btnStatus == 1) {//2、买跌
                    EventBus.getDefault().post(new EventDatas(EventContents.ALL_QUOTATION_ACTIVITY_TWO, ""));

                } else if (btnStatus == 2) {//3、挂单
                    EventBus.getDefault().post(new EventDatas(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_FOUR, ""));

                }
                break;
            case R.id.ll_chart:
                if (userId == -1) {
                    showMyToast("请先登录");
                } else {
                    String chartRoomId = SpUtils.getString(this, "chartRoomId");
                    if (!TextUtils.isEmpty(chartRoomId))
                        RongIM.getInstance().startConversation(this, Conversation.ConversationType.CHATROOM, chartRoomId, "聊天室");
                    else
                        BaseUtils.showToast("初始化失败", this);
                }
                break;
        }
    }

    /**
     * 控制Fragment的显示与隐藏
     *
     * @param index
     */
    private void setIndexSelected(int index) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (index == 0) {
            ft.hide(advancedTransFragment);
            ft.show(simpleTransFragment);
        } else {
            ft.hide(simpleTransFragment);
            ft.show(advancedTransFragment);
        }
        ft.commit();
    }

    private void changeStatus(int tag) {
        if (tag == 0) {
            tvAnanlyze.setTextColor(getResources().getColor(R.color.white));
            tvAnanlyze.setBackgroundResource(R.mipmap.all_quotation_left_fill);
            tvMsg.setTextColor(getResources().getColor(R.color.main_color));
            tvMsg.setBackgroundResource(R.mipmap.all_quotation_right_side);
        } else {
            tvAnanlyze.setTextColor(getResources().getColor(R.color.main_color));
            tvAnanlyze.setBackgroundResource(R.mipmap.all_quotation_side_left);
            tvMsg.setTextColor(getResources().getColor(R.color.white));
            tvMsg.setBackgroundResource(R.mipmap.all_quotation_right_fill);
        }

    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {

    }

    @Override
    public void showDialog() {

    }

    @Override
    public void dismissDialog() {

    }

    @Override
    public void showMyToast(String str) {

    }

    @Override
    public void setSymbolCalInfoData(SymbolInfo symbolInfo) {
        this.symbolInfo = symbolInfo;
        if (symbleTwo.equals(symbolInfo.getProfitCalCurrency()))
            symbleTwo += "," + symbolInfo.getMarginCalCurrency();
        else
            symbleTwo += "," + symbolInfo.getMarginCalCurrency() + "," + symbolInfo.getProfitCalCurrency();

        if (simpleTransFragment != null) {
            simpleTransFragment.setSymbolCalInfoDatas(symbolInfo);
        }
        if (advancedTransFragment != null) {
            advancedTransFragment.setSymbolCalInfoDatas(symbolInfo);
        }
        mainPresent.startRealTimeQuote(symbleTwo);
    }

    @Override
    public void setTradeOpenData(OpenTrader openTrader) {

    }

    @Override
    public void setPendingOrderData(PendingOrder pendingOrder) {

    }

    @Override
    public void setSymbolPrice(SymbolPrice symbolPrice) {
        if (simpleTransFragment != null)
            simpleTransFragment.setBaseData(symbolPrice);
        if (advancedTransFragment != null)
            advancedTransFragment.setBaseData(symbolPrice);
    }

    /**
     * 实时数据
     *
     * @param quoteBeen
     */
    @Override
    public void setData(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {
        if (simpleTransFragment != null && whatTab == 0)
            simpleTransFragment.setRealPrice(quoteBeen);
        if (advancedTransFragment != null && whatTab == 1)
            advancedTransFragment.setRealPrice(quoteBeen);
    }

    /**
     * 根据开仓或者挂单的状态进行处理
     *
     * @param tag
     */
    public void setBtnTradeTextAndColor(int tag) {
        if (tag == 0) {//买涨
            btnStatus = 0;
            btnTrade.setText("确定买入");
            btnTrade.setBackgroundColor(getResources().getColor(R.color.main_color));
        } else if (tag == 1) {//买跌
            btnStatus = 1;
            btnTrade.setText("确定卖出");
            btnTrade.setBackgroundColor(getResources().getColor(R.color.main_color));
        } else {//挂单
            btnStatus = 2;
            btnTrade.setText("确定挂单");
            btnTrade.setBackgroundColor(getResources().getColor(R.color.main_color));
        }
    }

    public void noLoginGoThere() {
        BaseUtils.showToast("您尚未登录", this);
    }
}
